//go:build windows

package pcnet

import (
	"bufio"
	"encoding/json"
	"fmt"
	psnet "github.com/shirou/gopsutil/v3/net"
	"github.com/urfave/cli/v2"
	"net"
	"os"
	"strings"
)

type NetworkInfo struct {
	IP      string
	MAC     string
	DNS     string
	Gateway string
}

var (
	BuildTime string
	Version   = "1.0.0"
)

func Do() {
	app := cli.NewApp()
	app.Name = "idp-network-cli"
	app.Version = fmt.Sprintf("%s build:%s", Version, BuildTime)
	app.Usage = "为 idp 获取网络信息提供支持"
	app.Description = "网络信息包括：获取当前正在工作的网卡信息，获取正在上网的网卡的ip地址 "
	app.Flags = []cli.Flag{
		&cli.BoolFlag{
			Name:        "net",
			Aliases:     []string{"n"},
			Usage:       "当前的活跃网卡信息",
			DefaultText: "true",
			Action: func(ctx *cli.Context, b bool) error {
				r, err := getInfo()
				if err != nil {
					return err
				}
				var mbs []byte
				if mbs, err = json.Marshal(r); err != nil {
					return err
				}
				w := bufio.NewWriter(os.Stdout)
				w.Write(mbs)
				w.WriteString("\n")
				return w.Flush()

			},
		},
		&cli.BoolFlag{
			Name:    "ip",
			Aliases: []string{"i"},
			Usage:   "检查进程",
			Action: func(ctx *cli.Context, b bool) error {
				ip, err := getOutBoundIP()
				if err != nil {
					return err
				}
				w := bufio.NewWriter(os.Stdout)
				w.Write([]byte(ip))
				w.WriteString("\n")
				return w.Flush()
			},
		},
	}
	app.Action = func(ctx *cli.Context) error {
		return nil
	}
	if err := app.Run(os.Args); err != nil {
		fmt.Printf("命令行调用错误：%s ，请查看帮助文档", err.Error())
	}

}

// select * from Win32_NetworkAdapterConfiguration WHERE IPEnabled = True 可用网卡信息
// 对比当前udp使用的网卡就知道是那个网卡详情
// https://learn.microsoft.com/zh-cn/windows/win32/cimwin32prov/win32-networkadapterconfiguration

func getInfo() (data NetworkInfo, err error) {
	var (
		ip string
		p  psnet.InterfaceStatList
	)
	if ip, err = getOutBoundIP(); err != nil {
		return
	}
	if p, err = psnet.Interfaces(); err != nil {
		return
	}
	for i := range p {
		fmt.Println(p[i])
	}
	data.IP = ip
	return data, nil
}

func getOutBoundIP() (ip string, err error) {
	var (
		conn net.Conn
	)
	conn, err = net.Dial("udp", "8.8.8.8:9999")
	if err != nil {
		return "", err
	}
	localAdd := conn.LocalAddr()
	ip = strings.Split(localAdd.String(), ":")[0]
	return ip, nil
}
